package com.shanxia.codec.cmd;

import com.shanxia.codec.ProtocolDataBase;
import com.shanxia.codec.enums.DecodeEnum;
import lombok.Data;

import java.util.Arrays;

import static com.shanxia.codec.Decoder.*;

/**
 * C -> S
 * 充电桩上报“即插即充” 启动充电结果
 */
@Data
public class Cmd210 extends ProtocolDataBase {

    public static final int MIN_SIZE = 41;

    private int v1;
    private int v2;
    private String sn;                          // 充电桩编码
    private int pileNum;                        // 充电枪号
    private int code;                           // 启动结果

    public Cmd210(){
        super.setCmd(210);
    }

    public static Cmd210 decodeFromBase(ProtocolDataBase protocolDataBase) {
        Cmd210 cmd = new Cmd210();
        cmd.copyDataFrom(protocolDataBase);
        byte[] dataField = protocolDataBase.getDataField();
        if (dataField.length < MIN_SIZE) {
            cmd.setResult(DecodeEnum.InvalidData);
            return cmd;
        }
        int offset = 0;
        cmd.v1 = getUint16(dataField, offset);
        offset += 2;
        cmd.v2 = getUint16(dataField, offset);
        offset += 2;
        // 32字节充电桩编码
        cmd.sn = byteToAscii(Arrays.copyOfRange(dataField, offset, offset + 32), true);
        offset += 32;
        // 1字节充电抢号
        cmd.pileNum = getUint8(dataField[offset++]);
        // 4字节启动结果
        cmd.code = bytesToIntLittle(dataField, offset);
        return cmd;
    }

    @Override
    public String toString() {

        StringBuffer buffer = new StringBuffer();
        buffer.append("#cmd210#").append("\n");
        buffer.append("v1:").append(v1).append("\n");
        buffer.append("v2:").append(v2).append("\n");
        buffer.append("充电桩编码:").append(sn).append("\n");
        buffer.append("充电枪号:").append(pileNum).append("\n");
        buffer.append("启动结果:").append(code).append("\n");
        return buffer.toString();
    }
}
